package com.github.defense.starter.zuul.filter;

import com.github.defense.common.request.DefenseRequest;
import com.github.defense.plugin.base.DefensePlugin;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.springframework.core.Ordered;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lettger
 * @Date: 2021/12/13 上午10:06
 */
@Slf4j
public class PluginPreZuulFilter extends ZuulFilter implements Ordered {

    private final List<DefensePlugin> plugins;

    public PluginPreZuulFilter(final List<DefensePlugin> plugins) {
        this.plugins = loadPlugins(plugins);
    }

    /**
     * 插件排序
     *
     * @param plugins
     * @return
     */
    private static List<DefensePlugin> loadPlugins(List<DefensePlugin> plugins) {
        return plugins
                .stream()
                .sorted(Comparator.comparingInt(DefensePlugin::getOrder))
                .collect(Collectors.toList());
    }

    @Override
    public String filterType() {
        return null;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        DefenseRequest defenseRequest = new DefenseRequest();

        HttpServletRequest request = context.getRequest();
         defenseRequest.setParams(context.getRequestQueryParams());
         return null;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
